//
//  LoginViewController.m
//  001LiycSinaWeiBo
//
//  Created by 李伟国 on 15/9/8.
//  Copyright (c) 2015年 李伟国. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()<UIWebViewDelegate>
{
    UIWebView *_loginWebView;//用于加载登陆界面
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"登陆";
    
    UIBarButtonItem *cancelLoginItem = [[UIBarButtonItem alloc] initWithTitle:@"取消登陆" style:UIBarButtonItemStylePlain target:self action:@selector(cancelLogin:)];
    self.navigationItem.leftBarButtonItem = cancelLoginItem;
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _loginWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDHT, SCREEN_HEIGHT - 64)];
    _loginWebView.delegate = self;
    [self.view addSubview:_loginWebView];
    
//    获取到授权登陆完整的URL
    NSURL *authorizeURL = [Help getAuthorizeURL];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:authorizeURL];
    
//    加载request
    [_loginWebView loadRequest:request];
    
    
}

#pragma mark --取消登陆 
- (void)cancelLogin:(UIBarButtonItem*)item {

    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark --UIWebViewDelegate
//将要请求时回调
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%s",__func__);
    
    
    NSString *path = [request.URL absoluteString];
    
//    http://hi.baidu.com/jt_one#access_token=2.008kmTQDjoxjvDbce659177bPQkUGD&remind_in=125685&expires_in=125685&uid=2991918775
    
    NSArray *array = [path componentsSeparatedByString:@"#"];
    
    
    
    if (array.count > 1) {
//        登陆成功，已经获取到token，uid，expires_in
        
        
//        发送通知
        NSNotification *noti = [NSNotification notificationWithName:LOGIN_SUCESS object:path];
        [[NSNotificationCenter defaultCenter] postNotification:noti];
        
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        return NO;
    }
    
    NSLog(@"====%@",path);
    
    
    
    return YES;
}
//开始请求时回调
- (void)webViewDidStartLoad:(UIWebView *)webView {

    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    [MMProgressHUD showWithTitle:@"Loading..." status:@"     "];
}
//请求成功时回调
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [MMProgressHUD dismissWithSuccess:@"Success!"];
}
//请求失败时回调
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [MMProgressHUD dismissWithSuccess:@"Success!"];
}
@end



